/*
Copyright (c) 2014, ebaklund
All rights reserved.

Redistribution and use in source and binary forms, with or without modification, 
are permitted provided that the following conditions are met:

1. Redistributions of source code must retain the above copyright notice, 
   this list of conditions and the following disclaimer.

2. Redistributions in binary form must reproduce the above copyright notice, 
   this list of conditions and the following disclaimer in the documentation 
   and/or other materials provided with the distribution.

3. Neither the name of the <ORGANIZATION> nor the names of its contributors 
   may be used to endorse or promote products derived from this software 
   without specific prior written permission.

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" 
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE 
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE 
ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE 
LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR 
CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF 
SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS 
INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN 
CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) 
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE 
POSSIBILITY OF SUCH DAMAGE.
*/


#include <Do/Sys/Gui/Win32/GLWidget.h>
#include <Do/Sys/Win32/GlCtx.h>
#include <Do/Sys/ErrorException.h>
#include <Do/Sys/TimePoint.h>

#include <Do/Flow/EagerSignalImpl.hh>
#include <Do/Flow/EagerSlotImpl.hh>
#include <Do/GL/GlEvent.h>
#include <Do/GL/GlViewport.h>
#include <Do/GL/GlMatrix4.hh>

#include <Do/SyntacticCandy.h>
#include <Do/Str.h>
#include <Do/IroPropertyImpl.hh>
#include <Do/IrwPropertyImpl.hh>
#include <Do/ErwPropertyImpl.hh>
#include <Do/Gui/PaintInfo.h>
#include <Do/Gui/Viewport.h>
#include <Do/Primitives/Color4f.h>
#include <Do/Primitives/Pnt2.hh>
#include <Do/Primitives/Size2.hh>

#include <Windows.h>
#include <assert.h>
#include <memory>

using Do::Primitives::Pnt2u;
using Do::Primitives::Pnt2i;
using Do::Primitives::Size2u;
using Do::Primitives::Size2i;
using Do::Primitives::Rect2u;
using Do::Primitives::Rect2i;
using Do::Primitives::Color4f;
using Do::Gui::PaintInfo;
using Do::Gui::Viewport;
using Do::Sys::TimePoint;
using Do::Gl::GlEvent;
using Do::Gl::GlViewport;

/******************************************************************************/
/* IMPL DECL                                                                  */               
/******************************************************************************/


class Do::Sys::Gui::Win32::GLWidget::Impl
  {
  private:

#pragma region PRIVATE DATA GLWidget::Impl

    int pfi_;
    Do::Sys::Win32::GlCtx gl_ctx_;

#pragma endregion

#pragma region PRIVATE STATIC GlWidget::Impl

  static PIXELFORMATDESCRIPTOR const& getGlPixFormatDesc()
    {
      static PIXELFORMATDESCRIPTOR pfd = 
        { 
          sizeof(pfd),           // size of this pfd  
          1,                     // version number  
          PFD_DRAW_TO_WINDOW |   // support window  
          PFD_SUPPORT_OPENGL |   // support OpenGL  
          PFD_DOUBLEBUFFER,      // double buffered  
          PFD_TYPE_RGBA,         // RGBA type  
          32,                    // color depth  
          0, 0, 0, 0, 0, 0,      // color bits ignored  
          0,                     // no alpha buffer  
          0,                     // shift bit ignored  
          0,                     // no accumulation buffer  
          0, 0, 0, 0,            // accum bits ignored  
          32,                    // z-buffer depth
          0,                     // no stencil buffer  
          0,                     // no auxiliary buffer  
          PFD_MAIN_PLANE,        // main layer  
          0,                     // reserved  
          0, 0, 0                // layer masks ignored  
      }; 

      return pfd;
    }

  static int initGlPixFormat(HWND hwnd)
    {
      HDC hdc = GetDC(hwnd);
      PIXELFORMATDESCRIPTOR const* ppfd = &getGlPixFormatDesc();
      int pfi = ChoosePixelFormat(hdc, ppfd);
      BOOL has_pfd = SetPixelFormat(hdc, pfi, ppfd);

      assert(has_pfd);      
      assert(GetLastError() == NO_ERROR);  

      return pfi;
    }

#pragma endregion

  public:

#pragma region INTERNAL STATIC GlWidget::Impl

    static LPWSTR getWndClassName()
      {
        return L"Do_Gui_GLWidget";
      }

    static DWORD getWndClassStyle()
      {
        return CS_OWNDC;
      }

    static DWORD getWndWindowStyle()
      {
        return WS_OVERLAPPEDWINDOW | WS_CLIPSIBLINGS | WS_CLIPCHILDREN;
      }

#pragma endregion

#pragma region PRIVATE GlWidget::Impl

    void handleSize(Size2u const& size2u) 
      {
        GlEvent gl_event(TimePoint::now(), this->gl_ctx_, GlViewport() <<= size2u);
        handlePaint(gl_event);
      }

    void handlePaint(PaintInfo const& paint_info) 
      {
        GlEvent gl_event(TimePoint::now(), this->gl_ctx_, GlViewport() <<= paint_info.window_size);
        handlePaint(gl_event);
      }

    void handlePaint(GlEvent& gl_event) 
      {
        glViewport <<= gl_event.viewport;

        glMatrixMode(GL_PROJECTION);
        glLoadIdentity();
        glFrustum(-1.0,1.0,-1.0,1.0,1.5,10.0);
        glMatrixMode(GL_MODELVIEW);

        glClearColor <<= Color4f() <<= clearColor;
        glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);

        glDrawSignal.push(gl_event);
        SwapBuffers(gl_event.binder.hdc());
      }

#pragma endregion

#pragma region INTERNAL GlWidget::Impl

    Impl(HWND hwnd)
      : pfi_(initGlPixFormat(hwnd)),
        gl_ctx_(hwnd)
      {
        sizeSlot  >>= [this] (Size2u const& size) { this->handleSize(size); };
        paintSlot >>= [this] (PaintInfo const& paint_info) { this->handlePaint(paint_info); };
      }

    ~Impl()
      {}

    void glPerform(std::function<void (GlEvent const& gl_event)> const& gl_work, Size2u window_size)
      {
        if (!gl_work)
          return;

        GlEvent gl_event(TimePoint::now(), this->gl_ctx_, GlViewport() <<= window_size);

        gl_work(gl_event);
      }

    Do::Flow::EagerSlotImpl<Size2u>       sizeSlot;
    Do::Flow::EagerSlotImpl<PaintInfo>    paintSlot;

    Do::Flow::EagerSignalImpl<GlEvent>  glDrawSignal;

    Do::ErwPropertyImpl<Color4f>            clearColor;

#pragma endregion

  };


#pragma region PUBLIC GLWidget

Do::Sys::Gui::Win32::GLWidget::GLWidget()
  : Core(Impl::getWndClassName(), Impl::getWndClassStyle(), Impl::getWndWindowStyle()),
    _ (new Impl(hwnd())),
    glDrawSignal(_->glDrawSignal),
    clearColor(_->clearColor)
  {
    Core::paintSignal >>= _->paintSlot;
    Core::sizeSignal  >>= _->sizeSlot;

    clearColor <<= Color4f(0.0f, 0.0f, 0.0f, 1.0f);
  }

Do::Sys::Gui::Win32::GLWidget::~GLWidget()
  {
    delete _ ;
    _ = nullptr;
  }

void Do::Sys::Gui::Win32::GLWidget::glPerform(std::function<void (Do::Gl::GlEvent const&)> const& gl_work) const
  {
    _->glPerform(gl_work, Size2u() <<= RECT() <<= this->windowRect);
  }


#pragma endregion